package com.example.knowman.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.knowman.ReturnMessage.*;
import com.example.knowman.dao.knowLabelMainEx;
import com.example.knowman.dao.knowMainEx;
import com.example.knowman.entity.knowArchFiles;
import com.example.knowman.entity.knowLabelMain;
import com.example.knowman.service.ILog4operateService;
import com.example.knowman.service.IknowArchFilesService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

//9.2标签
@RestController
@RequestMapping("/knowArchFiles")
public class KnowArchFilesController {
    private final IknowArchFilesService iknowArchFilesService;

    private final ILog4operateService iLog4operateService;

    public KnowArchFilesController(IknowArchFilesService iknowArchFilesService,ILog4operateService iLog4operateService) {
        this.iknowArchFilesService = iknowArchFilesService;
        this.iLog4operateService = iLog4operateService;
    }


    //根据knowId返回所有附件信息(文件地址是否需要加密？)
    //查
    @GetMapping("getByKnowId")
    public ResponseEntity<MessageExKnowArchFiles> getByKnowId(@RequestParam Integer knowId) {

        List<knowArchFiles> res = iknowArchFilesService.getByKnowId(knowId);
        MessageExKnowArchFiles resMessage = new MessageExKnowArchFiles();
        resMessage.setData(res);
        resMessage.setCode(200);
        resMessage.setTip("查询成功");
        return ResponseEntity.ok(resMessage);

    }

    //新增
    @PostMapping("Insert")
    public ResponseEntity<Message> Insert(@RequestParam MultipartFile file,
                                          @RequestParam Integer knowId,
                                          @RequestParam String staffCode) {

        // 获取文件名
        String originalFilename = file.getOriginalFilename();
        // 获取不含后缀的文件名
        String filenameWithoutExtension = originalFilename.substring(0, originalFilename.lastIndexOf("."));
        // 获取文件大小
        long size = file.getSize();
        String res ="";
        DecimalFormat dec = new DecimalFormat("0.00");
        //处理大小
        double tempSize = (double) size;
        Integer level =0;
        while (tempSize>1024){
            tempSize/=1024.0;
            level++;
        }
        if(level==0){
            res = dec.format(tempSize).concat(" B");
        }
        else if(level==1){
            res = dec.format(tempSize).concat(" KB");
        }
        else if(level==2){
            res = dec.format(tempSize).concat(" MB");
        }
        else if(level==3){
            res = dec.format(tempSize).concat(" GB");
        }
        else if(level==4){
            res = dec.format(tempSize).concat(" TB");
        }
        else {
            res="文件过大";
        }
        // 打印文件信息
//            System.out.println("原始文件名: " + originalFilename);
//            System.out.println("不含后缀的文件名: " + filenameWithoutExtension);
//            System.out.println("文件大小: "+ res);
        String newFilename = staffCode + originalFilename;
        knowArchFiles item = new knowArchFiles();
        //这个url是保存进数据库的，到时候部署到服务器要改
        String URL = "http://124.223.214.155:81/files/Know/"+newFilename;
        //参考ip: http://localhost:81/files/   #http://124.223.214.155:81/files/
        item.setFileURL(URL);
        item.setKnowId(knowId);
        item.setFileSize(res);
        item.setFileName(originalFilename);


        //上传文件到服务器
//        File dest = new File("C:\\Users\\Administrator\\Desktop\\Files\\Know\\" + newFilename);
        File dest = new File("/home/digitalArch/Files/Know/" + newFilename);
        //上面的路径到时候也要进行修改，参考uploadPath: D:\\data\Files\     #/home/digitalArch/Files/  后面估计还有Know这个文件夹路径
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
        } catch (Exception e) {
            e.printStackTrace();
            Message upMes = new Message();
            upMes.setCode(100);
            upMes.setTip("文件上传失败！");
            return ResponseEntity.badRequest().body(upMes);
        }

        //log4
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request1 = attributes.getRequest();
        String ipAddress=request1.getHeader("ip");
        String operator=request1.getHeader("staffCode");
        String content = operator+"新增了一个知识附件信息，对应知识id:"+knowId;
        iLog4operateService.insertSingle(operator,content,ipAddress);
        //
        Message mes = iknowArchFilesService.insertItems(item);
        if (mes.getCode() == 200) {
            return ResponseEntity.ok(mes);
        } else {
            return ResponseEntity.badRequest().body(mes);
        }
    }

//    //新增
//    @PostMapping("testUpload")
//    public ResponseEntity<Message> testUpload(@RequestParam MultipartFile file,
//                                          @RequestParam Integer knowId,
//                                          @RequestParam String staffCode) {
//
//
//
//        iknowArchFilesService.Upload(file,knowId,staffCode);
//        return null;
//    }


    //下载文件
    @PostMapping ("Download")
    public void Download(@RequestParam String url, HttpServletResponse response) {

        iknowArchFilesService.downloadFile(url,response);

    }

    //下载次数+1
    @GetMapping("addDownloadCount")
    public ResponseEntity<Message> addDownloadCount(@RequestParam Integer archFilesId) {

        iknowArchFilesService.AddDCount(archFilesId);
        Message resMessage = new Message();
        resMessage.setCode(200);
        resMessage.setTip("下载次数+1");
        return ResponseEntity.ok(resMessage);

    }

    //删除附件
    @GetMapping("deleteByarchFilesId")
    public ResponseEntity<Message> deleteByarchFilesId(@RequestParam Integer archFilesId) {

        Message mes  = iknowArchFilesService.deleteByarchFilesId(archFilesId);


        //log4
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request1 = attributes.getRequest();
        String ipAddress=request1.getHeader("ip");
        String operator=request1.getHeader("staffCode");
        String content = operator+"删除了一个知识附件信息，archFilesId:"+archFilesId;
        iLog4operateService.insertSingle(operator,content,ipAddress);
        //
        if (mes.getCode() == 200) {
            return ResponseEntity.ok(mes);
        } else {
            return ResponseEntity.badRequest().body(mes);
        }

    }
}
